import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'
import getPageTitle from './utils/get-page-title'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  // 有token
  const token = store.getters.token

  if (token) {
    to.path === '/login' ? next('/') : next()
    !store.getters.userId && store.dispatch('user/saveUserInfoAction')
    NProgress.done()
    return
  }

  // 没有token
  if (whiteList.includes(to.path)) {
    next()
    NProgress.done()
    return
  } else {
    next('/login')
    Message.info('请先登录')
    NProgress.done()
    return
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
